package com.fadadianqi.search;

import com.fadadianqi.search.IndexPathHelper.IndexEnum;
import com.fadadianqi.logistics.sell.model.InOut;
import com.fadadianqi.logistics.sell.service.InOutService;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;

import java.util.List;

public class InOutIndexService extends AbstractIndexService {

    private static final Log log = LogFactory.getLog(InOutIndexService.class);

    private IndexPathHelper indexPathHelper = new IndexPathHelper(IndexEnum.IN_OUT);

    private String newPath;

    @Override
    protected void changeIndexPath() {
        indexPathHelper.savePath(newPath);
    }

    @Override
    public String getCurrentIndexPath() {
        return indexPathHelper.getIndexPath();
    }

    @Override
    protected String getNewIndexPath() {
        newPath = indexPathHelper.createNewPath();
        return newPath;
    }

    @Override
    protected void build(IndexWriter writer, boolean rebuild) throws Exception {
        synchronized (writer) {
            // 写操作保持同步
            int total = inOutService.countAll();
            int limit = 1000;
            int pages = total / limit;
            if (total % limit != 0) {
                pages++;
            }
            for (int page = 1; page <= pages; page++) {
                Pagination pagination = null;
                pagination = new Pagination(page, limit);
                List<InOut> list = inOutService.findAll(pagination);
                if (ValidatorHelper.isEmpty(list)) {
                    continue;
                }
                for (InOut inout : list) {
                    writer.addDocument(documentBuilder(inout));
                }
            }
            writer.optimize();
            writer.close(true);
        }
    }

    @Override
    protected Document documentBuilder(Object o) throws Exception {
        InOut inOut = (InOut) o;
        Document doc = new Document();

        Field id = new Field(InOut.PROP_ID, inOut.getId(), Store.YES, Index.NOT_ANALYZED);
        doc.add(id);

        Field memo = new Field(InOut.PROP_MEMO, inOut.getMemo(), Store.YES, Index.NOT_ANALYZED);
        doc.add(memo);

        if (log.isDebugEnabled()) {
            log.debug(doc.toString());
        }

        return doc;
    }

    private static Boolean IS_RUNNING = Boolean.FALSE;

    public synchronized boolean isRunning() {
        return IS_RUNNING;
    }

    protected synchronized void lock() {
        IS_RUNNING = true;
    }

    protected synchronized void unlock() {
        IS_RUNNING = false;
    }

    private InOutService inOutService;

}
